/*
 * @Author: doing
 * @Date: 2023-08-09 21:02:32
 * @LastEditors: git config user.name && git config user.email
 * @LastEditTime: 2023-08-26 14:22:59
 * @FilePath: \background-management-system\src\axios.js
 * @Description: 
 * 对axios进行封装
 * Copyright (c) 2023 by 1540265624@qq.com, All Rights Reserved. 
 */
import axios from "axios"
import { toast, showModal } from '~/composables/util'
import { getToken } from "~/composables/auth"
import store from "./store"

const baseURL = `${import.meta.env.VITE_PROXY_API}`;

const service = axios.create({
    baseURL
})

// 添加请求拦截器
service.interceptors.request.use(function (config) {

    // 往header头自动添加token
    const TokenKey = getToken()
    if(TokenKey.accessToken){
        config.headers["Authorization"] = `Bearer ${TokenKey.accessToken}`
    }
    return config;
  }, function (error) {
    console.log(error)
    return Promise.reject(error);
  });

// 添加响应拦截器
service.interceptors.response.use(function (response) {
    // 对响应数据做点什么,注意这里返回的是response.data.data!!!
    // 可以改为response
    const res = response.data
    // console.log(res)
    
    if (res.code !== 20000) {
      toast(res.message || 'Error', 'error', 5 * 1000)

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        showModal('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout','warning').then(() => {
          store.dispatch('resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return response
    }
  }, function (error) {
    // 非401状态码，则直接提示信息
    if (error.response && error.response.status !== 401) {
      toast( error.message,'error', 5 * 1000)
      return Promise.reject(error)
    }
    
    // 401 未认证或者访问令牌过期，未认证则要通过刷新令牌获取新的认证信息
    let isLock = true // 防止重复发送刷新请求
    const PcCookie = getToken()
    if (isLock && PcCookie.refreshTokenKey) {
      isLock = false // 在发送后，将此值 设置为false
      // 跳转到认证中心客户端，实现刷新令牌效果
      window.location.href =`${process.env.VITE_AUTH_CENTER_URL}/refresh?redirectURL=${window.location.href}`
    } else {
      //没有刷新令牌，则跳转到认证客户端进行重新认证
      window.location.href =`${process.env.VITE_AUTH_CENTER_URL}?redirectURL=${window.location.href}`
    }

    return Promise.reject('身份过期，重新认证')
 })

export default service



